#include "myopus.h"
myOpus::myOpus(int sampleRate,int channels,int samplesize)
{
    m_sampleRate = sampleRate;
    m_channels = channels;
    m_sampleSize = samplesize;
    int err = 0;
    m_encoder = opus_encoder_create(m_sampleRate, m_channels, OPUS_APPLICATION_VOIP, &err);

    m_decoder = opus_decoder_create(m_sampleRate, m_channels, &err);
    opus_decoder_ctl(m_decoder, OPUS_SET_LSB_DEPTH(samplesize));
}
myOpus::~myOpus()
{
    if(m_encoder)
        opus_encoder_destroy(m_encoder);
    if(m_decoder)
        opus_decoder_destroy(m_decoder);
}

int myOpus::Pcm2Opus_Enc(unsigned char *pcmdata,int pcmlen,unsigned char *opusdata,int opuslen)
{
    if(!m_encoder)
        return 0;
    int frame_size = (m_sampleRate*m_channels)/50;
    int nbBytes = opus_encode(m_encoder, (opus_int16 *)pcmdata, frame_size, opusdata, opuslen);
    return nbBytes;
}

int myOpus::Opus2Pcm_Dec(unsigned char *opusdata,int opuslen,unsigned char *pcmdata,int pcmlen)
{
    if(!m_decoder)
        return 0;
    int frame_size = (m_sampleRate*m_channels)/50;
    //解码，如果frameSize小于0，那么说明解码失败
    int framesize = opus_decode(m_decoder, opusdata, opuslen, (opus_int16 *)pcmdata, frame_size, 0);
    return framesize*m_channels*(m_sampleSize/8);
}

char *myOpus::GetlibOpusVersion()
{
    const char *tmp = opus_get_version_string();
    return (char *)tmp;
}
